package cn.lj.security;

import cn.hutool.core.util.ObjectUtil;
import cn.lj.entity.User;
import cn.lj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @file: UserDetailServiceImpl
 * @version: 1.0
 * @Description: 从数据库中获取数据的，重新定义这个查用户数据的过程，需要重写UserDetailsService接口。
 * 代码目的，作用，如何工作
 * @author: 李津
 * @date: 2021-05-22 12:48
 * 本代码要注意的事项、备注事项等
 */

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserService userService;

    @Autowired
    public UserDetailServiceImpl(UserService userService) {
        this.userService = userService;
    }

    /**
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getByUserName(username);

        if (ObjectUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("用户名或密码不正确");
        }

        return new AccountUser(user.getId(), user.getUsername(), user.getPassword(),
                getUserAuthority(user.getId()));
    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     *
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId) {

        // 角色(ROLE_admin)、菜单操作权限 sys:user:list
        String authority = userService.getUserAuthorityInfo(userId); // ROLE_admin,ROLE_normal,sys:user:list,....

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
